<template>
  <Modal :width="1000" v-model:visible="open" @ok="handleSuccess" title="图标宏控件">
    <div class="m-5">
      <div>
        <Checkbox v-model:checked="newData.isOnlyIcon">只显示图标，不显示名称</Checkbox>
      </div>
      <div class="text-right mb-2">
        <a-button type="primary" @click="handleCreate">增加</a-button>
      </div>
      <div>
        <Empty
          :image="simpleImage"
          v-if="!newData || !newData.options || newData.options.length == 0"
        />
      </div>
      <draggable
        v-model="newData.options"
        :component-data="{
          type: 'transition-group',
        }"
        :animation="180"
        handle=".draggable-macro-icon-ctl"
      >
        <template #item="{ element, index }">
          <div class="flex justify-between mb-2">
            <div class="w-230px flex items-center">
              图标
              <Select
                v-model:value="element.icon"
                :get-popup-container="getPopupContainer"
                :options="imgList"
                allow-clear
                style="width: 160px; margin-left: 6px"
              >
                <SelectOption v-for="item in imgList" :key="item.value" :value="item.value">
                  {{ item.label }}
                </SelectOption>
              </Select>
              <Image :src="getIcon(element.icon)" style="width: 30px; margin-left: 5x" />
            </div>
            <div
              >值 <Input v-model:value="element.value" style="width: 160px; margin-left: 6px"
            /></div>
            <div
              >名称 <Input v-model:value="element.name" style="width: 160px; margin-left: 6px"
            /></div>
            <div
              ><Radio
                v-model:checked="element.selected"
                @change="handleRadioChange($event, index)"
              />
              选中
            </div>
            <div class="ml-2">
              <close-outlined class="cursor-pointer" @click="hadnleDelete(index)" />
              <drag-outlined class="ml-2 cursor-pointer draggable-macro-icon-ctl" />
            </div>
          </div>
        </template>
      </draggable>
    </div>
  </Modal>
</template>
<script setup lang="ts">
  import { ref, PropType, computed, watch, onMounted } from 'vue';
  import { Modal, Input, Select, Radio, Empty, Image, Checkbox } from 'ant-design-vue';
  import draggable from 'vuedraggable';
  import { CloseOutlined, DragOutlined } from '@ant-design/icons-vue';
  import { isArray } from '/@/utils/is';
  import path from 'path';
  import fs from 'fs-extra';
  import { getIconSymbolList } from '/@/api/macro/macro';
  import { getShowImgInJar } from '/@/api/system/system';
  import { bufToUrl } from '/@/utils/file/base64Conver';

  const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;
  const SelectOption = Select.Option;
  const imgList = ref<any[]>([]);

  // let directoryPath = '/resource/images/symbol/symbol.json'; // 替换为实际的目录路径
  // // 因为手机端用的是后端的，所以仍然得通过后端获取图片
  // getSymbolList(directoryPath);
  // async function getSymbolList(path: any) {
  //   try {
  //     const response = await fetch(directoryPath);
  //     imgList.value = await response.json();
  //     console.log('getSymbolList data', imgList);
  //   } catch (error) {
  //     console.error('Error fetching data:', error);
  //   }
  // }

  async function getSymbolList() {
    const list = await getIconSymbolList();
    for (let i in list) {
      let fileName = list[i];
      let p = fileName.lastIndexOf('/');
      if (p > 0) {
        fileName = fileName.substring(p + 1);
      }

      let buf;
      await getShowImgInJar({ path: list[i] }).then((res) => {
        buf = bufToUrl(res)!;
      });
      imgList.value.push({
        iconBuf: buf,
        value: fileName,
        label: fileName,
        selected: false,
      });
    }
    console.log('getSymbolList data', imgList);
  }

  const getIcon = (value) => {
    let ary = imgList.value.filter((item) => {
      return item.value == value;
    });
    console.log('getIcon', ary);
    return ary && ary.length > 0 ? ary[0].iconBuf : '';
  };

  onMounted(() => {
    getSymbolList();
  });

  const emit = defineEmits(['success', 'update:visible']);
  const props = defineProps({
    visible: {
      type: Boolean as PropType<Boolean>,
      default: false,
    },
    data: {
      type: Array,
      default: () => [],
    },
  });

  const open = computed({
    get() {
      return props.visible;
    },
    set(e) {
      emit('update:visible', e);
    },
  });
  // const newData = ref<any[]>([]);
  const newData = ref<Recordable>({});
  watch(
    () => props.data,
    (newVal) => {
      newData.value = {
        options: [],
      };
      if (newVal && isArray(newVal.options)) {
        newData.value = JSON.parse(JSON.stringify(newVal));
      }
    },
    {
      immediate: true,
    },
  );
  const handleClose = () => {
    open.value = false;
  };

  const handleSuccess = () => {
    emit('success', newData.value);
    handleClose();
  };

  const handleCreate = () => {
    if (!newData.value.options) {
      newData.value.options = [];
    }
    newData.value.options.push({
      icon: '',
      value: '',
      label: '',
      selected: false,
    });
  };

  const hadnleDelete = (index) => {
    newData.value.options.splice(index, 1);
  };

  /**
   * @description: 处理只选中一个
   * @param {*} e
   * @param {*} index
   * @return {*}
   */
  const handleRadioChange = (e, index) => {
    newData.value.options.forEach((item, i) => {
      if (i != index) {
        item.selected = false;
      }
    });
  };

  const getPopupContainer = (triggerNode) => triggerNode?.parentNode;
</script>
